package main

import (
	"fmt"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"time"
)

//Sync() 方法通常用于确保在程序退出或在某个时间点之前，日志消息被完全刷新和记录。它将任何挂起的日志消息写入到日志文件或目标（如控制台）中。

func example() {
	option := zap.Fields(
		zap.String("log_name", "testlog"),
		zap.String("log_author", "prometheus"),
	)
	logger := zap.NewExample(option)

	logger.Debug("this is debug message")

	logger.Info("this is info message")

	logger.Info("this is info message with fileds", zap.Int("age", 37), zap.String("agender", "man"))

	logger.Warn("this is warn message")

	logger.Error("this is error message")
}

func exampleForHook() {
	option := zap.Hooks(func(entry zapcore.Entry) error {
		fmt.Println("[zap.Hooks]test Hooks")
		return nil
	})

	logger := zap.NewExample(option)

	defer logger.Sync()

	logger.Info("test output")

	logger.Warn("warn info")
}

func development() {
	logger, _ := zap.NewDevelopment()

	defer logger.Sync()

	logger.Info("failed to fetch url",
		// 强类型字段
		zap.String("url", "http://example.com"),
		zap.Int("attempt", 3),
		zap.Duration("duration", time.Second),
	)

	logger.With(
		// 强类型字段
		zap.String("url", "http://development.com"),
		zap.Int("attempt", 4),
		zap.Duration("duration", time.Second*5),
	).Info("[With] failed to fetch url")
}

func production() {
	logger, _ := zap.NewProduction()

	defer logger.Sync()

	url := "http://zap.uber.io"
	sugar := logger.Sugar()

	sugar.Infow("failed to fetch URL",
		"url", url,
		"attempt", 3,
		"time", time.Second,
	)

	sugar.Infof("Failed to fetch URL: %s", url)

	// 或更简洁 Sugar() 使用
	// sugar := zap.NewProduction().Sugar()
	// defer sugar.Sync()
}

func main() {
	//version1()

	//exampleForHook()

	//development()

	production()
}
